package com.imooc.ad.index.adunit;

import com.imooc.ad.index.IndexAwre;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class AdUnitIndex implements IndexAwre<Long, AdUnitObject> {

    private static Map<Long ,AdUnitObject> indexMapUnit;

    static {
        indexMapUnit = new ConcurrentHashMap<>();
    }

    @Override
    public AdUnitObject get(Long key) {
        return indexMapUnit.get(key);
    }

    @Override
    public void add(Long key, AdUnitObject value) {
        log.info("before add: {}",indexMapUnit);
        indexMapUnit.put(key, value);
        log.info("after add: {}",indexMapUnit);
    }

    @Override
    public void update(Long key, AdUnitObject value) {
        log.info("before update: {}", indexMapUnit);

        AdUnitObject oldUnit = indexMapUnit.get(key);
        if (null != oldUnit){
            indexMapUnit.put(key, value);
        } else {
            oldUnit.update(value);
        }

        log.info("after add: {}",indexMapUnit);
    }

    @Override
    public void delete(Long key, AdUnitObject value) {
        log.info("before delete: {}", indexMapUnit);
        indexMapUnit.remove(key);
        log.info("after delete: {}", indexMapUnit);
    }
}
